package com.xsq.wifi.activity;

import android.content.ContentUris;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.PopupWindow;
import android.widget.Toast;

import androidx.appcompat.app.AlertDialog;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.xsq.wifi.R;
import com.xsq.wifi.adapter.VideoGridAdapter;
import com.xsq.wifi.callback.Callbacks;
import com.xsq.wifi.databinding.ActivityUploadVideoBinding;
import com.xsq.wifi.model.VideoItem;
import com.xsq.wifi.utils.PCPClient;
import com.xsq.wifi.utils.PCPFileTransfer;
import com.xsq.wifi.utils.PCPLongLiveClient;
import com.xsq.wifi.utils.ProgressDialogUtil;
import com.xsq.wifi.utils.ToastUtil;
import com.xsq.wifi.utils.VideoConverter;
import com.xsq.wifi.utils.WifiListFetcher;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * 编写人：李振德
 * 创建时间：2025/6/1
 */
public class UploadVideoActivity extends BaseActivity {

    private static final String TAG = "UploadVideoActivity";
    private ActivityUploadVideoBinding binding;
    private List<VideoItem> videoList = new ArrayList<>();
    private VideoGridAdapter adapter;
    private String deviceIp;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityUploadVideoBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        deviceIp = getIntent().getStringExtra("deviceIp");
        loadVideosFromGallery();
        binding.backImg.setOnClickListener(view -> {
            finish();
        });
        binding.upButton.setOnClickListener(view -> {
            if(adapter.getSelectedVideos().size()==0){
                ToastUtil.show(UploadVideoActivity.this,"请选择视频");
            }else{
                showpopwindow();
                //ToastUtil.show(UploadVideoActivity.this,adapter.getSelectedVideos().size()+"");
            }
        });
    }

    private void loadVideosFromGallery() {
        String[] projection = {
                MediaStore.Video.Media._ID,
                MediaStore.Video.Media.DISPLAY_NAME,
                MediaStore.Video.Media.DURATION,
                MediaStore.Video.Media.SIZE,
                MediaStore.Video.Media.DATE_ADDED,
                MediaStore.Video.Media.DATA
        };

        String sortOrder = MediaStore.Video.Media.DATE_ADDED + " DESC";

        try (Cursor cursor = getContentResolver().query(
                MediaStore.Video.Media.EXTERNAL_CONTENT_URI,
                projection,
                null,
                null,
                sortOrder)) {

            if (cursor != null) {
                int idColumn = cursor.getColumnIndexOrThrow(MediaStore.Video.Media._ID);
                int nameColumn = cursor.getColumnIndexOrThrow(MediaStore.Video.Media.DISPLAY_NAME);
                int durationColumn = cursor.getColumnIndexOrThrow(MediaStore.Video.Media.DURATION);
                int sizeColumn = cursor.getColumnIndexOrThrow(MediaStore.Video.Media.SIZE);
                int pathColumn = cursor.getColumnIndexOrThrow(MediaStore.Video.Media.DATA);

                while (cursor.moveToNext()) {
                    long id = cursor.getLong(idColumn);
                    String name = cursor.getString(nameColumn);
                    long duration = cursor.getLong(durationColumn);
                    long size = cursor.getLong(sizeColumn);
                    String path = cursor.getString(pathColumn);

                    Uri contentUri = ContentUris.withAppendedId(
                            MediaStore.Video.Media.EXTERNAL_CONTENT_URI, id);

                    videoList.add(new VideoItem(id, name, duration, size, contentUri, path));
                }
            }
            // 更新UI显示视频列表
            setupVideoGrid();
        } catch (Exception e) {
            Log.e("VideoGallery", "获取视频失败", e);
            Toast.makeText(this, "获取视频失败", Toast.LENGTH_SHORT).show();
        }
    }

    private void setupVideoGrid() {
        RecyclerView recyclerView = findViewById(R.id.recyclerView);
        // 设置网格布局，每行3个
        GridLayoutManager layoutManager = new GridLayoutManager(this, 3);
        recyclerView.setLayoutManager(layoutManager);
        adapter = new VideoGridAdapter(videoList, this);
        recyclerView.setAdapter(adapter);
    }

    private void processSelectedVideos(List<VideoItem> selectedVideos) {
        // 这里可以获取选中的视频列表并进行处理
        for (VideoItem video : selectedVideos) {
            Log.d("SelectedVideo", "ID: " + video.getId() + ", Name: " + video.getName());
        }

        // 示例: 显示选中视频的信息
        StringBuilder sb = new StringBuilder();
        for (VideoItem video : selectedVideos) {
            sb.append(video.getName()).append("\n");
        }

        new AlertDialog.Builder(this)
                .setTitle("已选择的视频 (" + selectedVideos.size() + "个)")
                .setMessage(sb.toString())
                .setPositiveButton("确定", null)
                .show();
    }

    private void showpopwindow(){
        View chooseHeadView = LayoutInflater.from(UploadVideoActivity.this).inflate(R.layout.commit_vidoe_name_pop, null);
        PopupWindow popupWindow = new PopupWindow(chooseHeadView, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT, true);

        Button submit_button = (Button) chooseHeadView.findViewById(R.id.submit_button);
        Button cancel_button = (Button) chooseHeadView.findViewById(R.id.cancel_button);
        EditText bssidpassword = (EditText) chooseHeadView.findViewById(R.id.bssidpassword);

        cancel_button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popupWindow.dismiss();
            }
        });
        submit_button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ProgressDialogUtil.showProgressDialogText(UploadVideoActivity.this,"上传中...");
                WifiListFetcher.startFileTransfer(deviceIp,bssidpassword.getText().toString(), new Callbacks.ConfigCallback() {
                    @Override
                    public void onSuccess() {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                // 2. 选择本地视频文件
                                File inputFile = new File(adapter.getSelectedVideos().get(0).getPath());
                                File outputDir = getExternalFilesDir(null);
                                // 3. 转码为256x256的AVI
                                VideoConverter.convertToAVI(inputFile, outputDir, new VideoConverter.Callback() {
                                    @Override
                                    public void onSuccess(File aviFile) {
                                        // 初始化客户端
                                        PCPLongLiveClient client = new PCPLongLiveClient(deviceIp, 3333, 0xAA55, (byte)0x01);
                                        // 启动长连接
                                        try {
                                            client.start();
                                        } catch (IOException e) {
                                            Toast.makeText(UploadVideoActivity.this, "连接失败: " + e.getMessage(), Toast.LENGTH_SHORT).show();
                                            return;
                                        }
                                        client.sendFile(inputFile, new PCPLongLiveClient.PCPCallback() {
                                            @Override
                                            public void onProgress(int progress) {
                                                //runOnUiThread(() -> progressBar.setProgress(progress));
                                            }

                                            @Override
                                            public void onSuccess(byte[] response) {
                                                runOnUiThread(() -> Toast.makeText(UploadVideoActivity.this,
                                                        "传输完成: " + new String(response), Toast.LENGTH_SHORT).show());
                                            }

                                            @Override
                                            public void onFailure(String error) {
                                                runOnUiThread(() -> Toast.makeText(UploadVideoActivity.this,
                                                        "传输失败: " + error, Toast.LENGTH_SHORT).show());
                                            }
                                        });
                                    }
                                    @Override
                                    public void onFailure(String error) {
                                        Log.e("Converter", "转码失败: " + error);
                                    }
                                });
                                }
                            });
                        }

                    @Override
                    public void onFailure(String errorMsg) {
                        Log.v(TAG,errorMsg);
                        ProgressDialogUtil.dismiss();
                    }
                });
            }
        });
        setBackgroundAlpha(0.5f,popupWindow);
        popupWindow.setFocusable(true);
        popupWindow.setOutsideTouchable(false);
        popupWindow.showAtLocation(chooseHeadView, Gravity.CENTER,0,0);
    }

    private void setBackgroundAlpha(float bgAlpha,PopupWindow popupWindow) {
        WindowManager.LayoutParams lp = getWindow().getAttributes();
        lp.alpha = bgAlpha;//设置透明度（这是窗体本身的透明度，非背景）
        lp.dimAmount = bgAlpha;//设置灰度
        if (bgAlpha == 1) {
            getWindow().clearFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);//不移除该Flag的话,在有视频的页面上的视频会出现黑屏的bug
        } else {
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);//此行代码主要是解决在华为 红米米手机上半透明效果无效的bug
        }
        getWindow().setAttributes(lp);
        //监听弹窗
        popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                //弹窗关闭  dismiss()时恢复原样
                WindowManager.LayoutParams lp = getWindow().getAttributes();
                lp.alpha = 1f;
                getWindow().setAttributes(lp);
            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
    }
    @Override
    protected void onPause() {
        super.onPause();
    }
    @Override
    protected void onStop() {
        super.onStop();
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
    }
}

